package httpTools

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"net/http"
	Url "net/url"
	"time"
)

// Get 发送GET请求
// url 请求地址
// timeout 超时时间  秒，超时返回空
func Get(url string, timeout int) (response string, err error) {
	response = ""
	client := http.Client{Timeout: time.Duration(timeout) * time.Second}
	resp, error := client.Get(url)
	if error != nil {
		response = ""
		err = error
		return
	}
	defer resp.Body.Close()

	result, _ := ioutil.ReadAll(resp.Body)
	content := string(result)

	return content, nil
}

type ContentType string

const (
	ContenttypeJson ContentType = "application/json"
	ContenttypeUrl  ContentType = "application/x-www-form-urlencoded"
)

//发送POST请求
//url:请求地址，data:POST请求提交的数据,contentType:请求体格式，如：application/json
//content:请求放回的内容
func post(url string, data interface{}, contentType ContentType, timeout int) (content string, err error) {
	var params []byte
	if contentType == ContenttypeJson {
		params, _ = json.Marshal(data)
	} else {
		u, ok := data.(Url.Values)
		if ok {
			params = []byte(u.Encode())
		}
	}

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(params))

	if err != nil {
		return "", err
	}

	defer req.Body.Close()
	req.Header.Add("content-type", string(contentType))

	client := &http.Client{Timeout: time.Duration(timeout) * time.Second}
	resp, err2 := client.Do(req)
	if err2 != nil {
		return "", err2
	}
	defer resp.Body.Close()

	result, _ := ioutil.ReadAll(resp.Body)
	content = string(result)
	return
}

func PostJson(url string, data interface{}, timeout int) (content string, err error) {
	return post(url, data, ContenttypeJson, timeout)
}

func PostFormUrl(url string, data Url.Values, timeout int) (content string, err error) {
	return post(url, data, ContenttypeUrl, timeout)
}
